import React, { useState, useEffect } from "react";
import { Button, BackTop ,notification} from 'antd';
import { LeftOutlined, RightOutlined, RocketOutlined } from '@ant-design/icons'
// import { Button, notification } from 'antd';
import style from './css/chapterstyle.module.scss'
import { Link, useNavigate, useParams } from "react-router-dom";
import axios from 'axios'
export default function Chapterpage() {
    let obj = useParams()
    console.log(obj.zhangjie)
    const style2 = {
        height: 60,
        width: 60,
        lineHeight: '40px',
        borderRadius: 50,
        backgroundColor: '#d0cbc2',
        color: 'rgb(245,242,232)',
        textAlign: 'center',
        fontSize: 45,
    }
    let navigator = useNavigate(),
        [num, setNum] = useState(2),
        [flag2, setFlag2] = useState(false),
        [book_id, setBook_id] = useState(),
        [maxChapter, setMax] = useState(),
        [infodata, setData] = useState([]),
        [infodata2, setData2] = useState([]),
        [chp_text, setChptext] = useState(''),
        [theme_color, setColor] = useState('#f4eed9'),
        [flag, setFlag] = useState(false),
        temp = ['[。？！]”', '：(?=“)', '[。？！](?![^“”]*”)'].join('|'),
        reg = new RegExp('(' + temp + ')', 'g');
    function returnTwo(t) {
        return ('0' + t).toString().slice(-2);
    }
    function filterTime(value) {
        var t = new Date(value).getTime();
        var time = new Date(t);
        var Y = time.getFullYear();
        var M = returnTwo(time.getMonth());
        var D = returnTwo(time.getDate());
        var HH = returnTwo(time.getHours());
        var MM = returnTwo(time.getMinutes());
        var SS = returnTwo(time.getSeconds());
        return `${Y}-${M}-${D} ${HH}:${MM}:${SS}`
    }
    useEffect(() => {
        const message = async () => {
            setBook_id(obj.bookID)
            setNum(obj.zhangjie)
        }
        message()
    }, [obj])
    useEffect(() => {
        const fn = async () => {
            try {
                const result = await axios('/chapter/getinfo', { params: { bookId: obj.bookID, zhangjie: obj.zhangjie } })
                setMax(result.data[2])
                setData(result.data[0][0])
                setData2(result.data[1][0])
                setChptext(result.data[1][0].chapterText.replace(reg, '$1\<br>'))
                // console.log(result,111111111111)
            } catch (el) {
                return
            }
        }
        fn()
    }, [obj])

    let Previouschapter = async () => {
        navigator({ pathname: `/chapter/${obj.bookID}/${obj.zhangjie - 1}` })
        if (obj.zhangjie == 1) {
            alert('已经是第一章了')
            navigator({ pathname: `/chapter/${obj.bookID}/1 ` })
        }
    }
    let Nextchapter = async () => {
        navigator({ pathname: `/chapter/${obj.bookID}/${Number(obj.zhangjie) + 1}` })
        if (obj.zhangjie == maxChapter) {
            alert('已经是最新章了，没有更多了')
            navigator({ pathname: `/chapter/${obj.bookID}/${maxChapter}` })
        }
    }
    useEffect(() => {
        window.addEventListener('keydown', onkeydown)
        return () => {
            window.removeEventListener('keydown', onkeydown)
        }
    }, [num])

    const onkeydown = (el) => {
        if (el.keyCode === 37) {
            navigator({ pathname: `/chapter/${obj.bookID}/${obj.zhangjie - 1}` })
            if (obj.zhangjie == 1) {
                alert('已经是第一章了')
                navigator({ pathname: `/chapter/${obj.bookID}/1 ` })
            }
        } else if (el.keyCode === 39) {
            navigator({ pathname: `/chapter/${obj.bookID}/${Number(obj.zhangjie) + 1}` })
            if (obj.zhangjie == maxChapter) {
                alert('已经是最新章了，没有更多了')
                navigator({ pathname: `/chapter/${obj.bookID}/${maxChapter}` })
            }
        }
    }
    const changeFlag = () => {
        setFlag(!flag)
    }
    const changeColor = (bginfo) => {
        setColor(bginfo)
    }
    let toPerson = async () => {
        let res = await axios.get('/chapter/whetherlogin')
        if (res.data.code === 404) {
            alert('您还没有登录，请先登录')
            navigator({ pathname: '/login' })
        } else {
            navigator({ pathname: '/personal' })
        }
    }
    let bookrack = async () => {
        let res = await axios.get('/chapter/whetherlogin')
        if (res.data.code === 404) {
            alert('您还没有登录，请先登录')
            navigator({ pathname: '/login' })
        } else {
            navigator({ pathname: '/myBook' })
        }
    }
    let followbook = async () => {
        let res = await axios.get('/chapter/whetherlogin')
        if (res.data.code === 404) {
            alert('您还没有登录，请先登录')
            navigator({ pathname: '/login' })
        }
        else {
            setFlag2(!flag2)
            const eml = res.data.el
            let resdata = await axios('/chapter/insertinfo', { params: { n1: obj.bookID, n2: eml, n3: flag2 } })
        }
    }
    return (
        <div className={style.chapter_page} style={{ background: theme_color }}>
            <div className={style.header}>
                <span>
                    <Link to='/' className={style.cont}>酷匠网</Link>&gt;
                    <Link to={{pathname:`/xiangqing/${obj.bookID}`}} className={style.cont}>{infodata.name1}</Link>&gt;
                    <Link to={{pathname:`/directoryPage/${obj.bookID}`}} className={style.cont}>目录</Link>&gt;
                    <Link className={style.cont}>第{infodata2.zhangjie}章&nbsp;{infodata2.chapterName}</Link>
                </span>
            </div>
            <div className={style.content}>
                <div className={style.content_left}>
                    <Link to='/'>
                        <div className={style.icontags}>
                            <span className='iconfont icon-shouye'></span>
                            <p>首页</p>
                        </div>
                    </Link>

                    <div className={style.icontags} onClick={() => { toPerson() }}>
                        <span className='iconfont icon-gerenzhongxin'></span>
                        <p>个人中心</p>
                    </div>

                    <div className={style.icontags} onClick={() => { bookrack() }}>
                        <span className='iconfont icon-wodeshujia'></span>
                        <p>书架</p>
                    </div>

                    <div className={style.icontags} onClick={() => { followbook() }} style={{ color: flag2 ? '#1cace6' : 'black' }}>
                        <span className='iconfont icon-shoucangshuji'></span>
                        <p style={{ display: flag2 ? 'none' : 'block' }}>追书</p>
                        <p style={{ display: flag2 ? 'block' : 'none' }}>取消追书</p>
                    </div>

                    <Link to={{pathname:`/directoryPage/${obj.bookID}`}}>
                        <div className={style.icontags}>
                            <span className='iconfont icon-mulu'></span>
                            <p>目录</p>
                        </div>
                    </Link>
                    <div className={style.icontags} onClick={()=>{navigator({pathname:`/xiangqing/${obj.bookID}`})}}>
                        <span className='iconfont icon-pinglun'></span>
                        <p>评论</p>
                    </div>
                    <div className={style.icontag_2} onClick={() => { changeFlag() }}>
                        <span className='iconfont icon-shezhi'></span>
                        <p className={style.icontag_font}>背景</p>
                        <div className={style.themecolors} style={{ display: flag ? 'block' : 'none' }}>
                            <p onClick={() => { changeColor('#d5ebd5') }}></p>
                            <p onClick={() => { changeColor('#fff') }}></p>
                            <p onClick={() => { changeColor('#d0dfe5') }}></p>
                            <p onClick={() => { changeColor('#f4eed9') }}></p>
                        </div>
                    </div>
                </div>
                <div className={style.content_right}>
                    <h2>第{infodata2.zhangjie}章&nbsp;{infodata2.chapterName}</h2>
                    <div className={style.message}>
                        <span>小说：{infodata.name1}</span>
                        <span>作者：{infodata.userName}</span>
                        <span>更新时间：{filterTime(infodata2.chapterTime)}</span>
                    </div>
                    <div className={style.chapter_detail}>
                        <p dangerouslySetInnerHTML={{ __html: chp_text }}>
                        </p>
                    </div>
                </div>

            </div>
            <div className={style.tabbar}>
                <Button type="ghost" size="large"
                    style={{ width: '140px', borderRadius: '10px', boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.2)' }}
                    onClick={() => { Previouschapter() }}
                >
                    <LeftOutlined /> 上一章
                </Button>
                <Button type="ghost" size="large"
                    style={{ width: '140px', borderRadius: '10px', boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.2)' }}
                    onClick={() => { navigator({ pathname:`/directoryPage/${obj.bookID}`  }) }}
                >
                    目录
                </Button>
                <Button type="ghost" size="large"
                    style={{ width: '140px', borderRadius: '10px', boxShadow: '0px 0px 10px rgba(0, 0, 0, 0.2)' }}
                    onClick={() => { Nextchapter() }}
                >
                    下一章<RightOutlined />
                </Button>
            </div>
            <p className={style.bottomtips}>快捷键：左/右键 直接进入上/下一章</p>

            <BackTop>
                <div style={style2}>
                    <RocketOutlined style={{ marginTop: '8px' }} />
                </div>
            </BackTop>
        </div >
    )
}